<template>
  <a-spin :spinning="confirmLoading">
    <a-form class="antd-modal-form" v-bind="formItemLayout" ref="formRef">
      <a-row>
        <a-col :span="24">
          <a-form-item label="分配方式" v-bind="validateInfos.type">
            <j-dict-select-tag type='radio' v-model:value="formData.type" dictCode="distribution_type" placeholder="请选择分配方式" :disabled="disabled" @change="changeType"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="排查周期" v-bind="validateInfos.period">
	          <a-input-number v-model:value="formData.period" placeholder="请输入排查周期" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="周期单位" v-bind="validateInfos.periodUnit">
            <j-dict-select-tag type='radio' v-model:value="formData.periodUnit" dictCode="period_type" placeholder="请选择周期单位" :disabled="disabled" @change="changePeriodUnit"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="初始排查时间" v-bind="validateInfos.startTime">
		        <a-date-picker placeholder="请选择初始排查时间"  v-model:value="formData.startTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="工作日历" v-bind="validateInfos.calendar">
            <j-dict-select-tag type='radio' v-model:value="formData.calendar" dictCode="calendar_type" placeholder="请选择工作日历" :disabled="formData.periodUnit == 'periodType02' ? false : true"/>
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="formData.type == 'distributionType01'">
          <a-form-item label="排查人" v-bind="validateInfos.identifyPeople">
			      <j-select-user v-model:value="formData.identifyPeople" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="formData.type == 'distributionType02'">
          <a-form-item label="排查岗位" v-bind="validateInfos.identifyStation">
	          <j-search-select v-model:value="formData.identifyStation" dict="sys_position,name,code" :disabled="disabled" @change="changeIdentifyStation"/>
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="formData.periodUnit == 'periodType01'">
          <a-form-item label="工作开始日期" v-bind="validateInfos.workBeginTime">
            <a-time-picker  v-model:value="formData.workBeginTime" placeholder="请输入工作开始日期" value-format="HH:mm:ss"/>
            <!-- <a-input v-model:value="formData.workBeginTime" placeholder="请输入工作开始日期" :disabled="disabled"></a-input> -->
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="formData.periodUnit == 'periodType01'">
          <a-form-item label="工作结束日期" v-bind="validateInfos.workEndTime">
            <a-time-picker  v-model:value="formData.workEndTime" placeholder="请输入工作结束日期" value-format="HH:mm:ss"/>
            <!-- <a-input v-model:value="formData.workEndTime" placeholder="请输入工作结束日期" :disabled="disabled"></a-input> -->
          </a-form-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="最近下发时间" v-bind="validateInfos.latestTime">
		        <a-date-picker placeholder="请选择最近下发时间"  v-model:value="formData.latestTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col> -->
        <a-col :span="24">
          <a-form-item label="任务类型" v-bind="validateInfos.workType">
            <j-dict-select-tag type='radio' v-model:value="formData.workType" dictCode="risk_work_type" placeholder="请选择任务类型" :disabled="disabled" @change="changeWorkType"/>
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="formData.workType == '2' || formData.workType == '3' || formData.workType == '4'">
          <a-form-item label="包保任务对应项" v-bind="validateInfos.taskNum">
	          <j-search-select v-model:value="formData.taskNum" :dict="dictTaskNum" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <!-- <a-col :span="24">
          <a-form-item label="删除标志" v-bind="validateInfos.deleted">
            <j-dict-select-tag type='radio' v-model:value="formData.deleted" dictCode="yn" placeholder="请输入删除标志" :disabled="disabled"/>
          </a-form-item>
        </a-col> -->
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, onMounted, inject, defineProps, unref } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import JSelectUser from '/@/components/Form/src/jeecg/components/JSelectUser.vue';
  import { getValueType } from '/@/utils';
  import { tbBaseMeasuresTaskSaveOrUpdate,queryUserNameListByPositionCodes } from '../TbBaseControlMeasures.api';
  import { Form } from 'ant-design-vue';

  //接收主表id
  const mainId = inject('mainId');
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
        type: '',   
        period: undefined,
        periodUnit: '',   
        startTime: '',   
        calendar: '',   
        identifyPeople: '',   
        identifyStation: '',   
        workBeginTime: '',   
        workEndTime: '',   
        latestTime: '',   
        workType: '',   
        taskNum: '',   
        deleted: '',   
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const dictTaskNum = ref("tb_defend_risk_task_num,content,code");
  
  //表单验证
  const validatorRules = {
    type: [{ required: true, message: '请输入分配方式!'},],
    period: [{ required: true, message: '请输入排查周期!'},],
    periodUnit: [{ required: true, message: '请输入周期单位!'},],
    startTime: [{ required: true, message: '请输入初始排查时间!'},],
    calendar: [{ required: true, message: '请输入工作日历!'},],
    workType: [{ required: true, message: '请输入任务类型!'},],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const props = defineProps({
    disabled: { type: Boolean, default: false },
  });
  const formItemLayout = {
    labelCol: { xs: { span: 24 }, sm: { span: 5 } },
    wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
  };
  
  function changeWorkType(val){
    formData.taskNum = null;
    dictTaskNum.value = "tb_defend_risk_task_num,content,code,work_type='" + val +"'"
  }
  
  function changeIdentifyStation(val){
    queryUserNameListByPositionCodes(val)
      .then((responseResult) => {
        if(responseResult){
          formData.identifyPeople = responseResult.join(",")
        }else{
          formData.identifyPeople = null;
        }
        console.log("-----formData.identifyPeople--------------"+JSON.stringify(formData.identifyPeople))
      })
  }
  
  function changeType(val){
    formData.identifyPeople = null;
    formData.identifyStation = null;
  }
  
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData,tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
   
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    if (unref(mainId)) {
      model['riskMeasureId'] = unref(mainId);
    }
    await tbBaseMeasuresTaskSaveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  function changePeriodUnit(val) {
    if(val == "periodType01" || val == "periodType03" || val == "periodType04"){
      formData.calendar = 'calendarType01'
    }else{
      formData.calendar = null
    }
    console.log("--formData.calendar-------"+JSON.stringify(formData.calendar))
  }


  defineExpose({
    add,
    edit,
    submitForm,
    
    changeType,
    changeWorkType,
    changeIdentifyStation,
    dictTaskNum,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    height: 500px !important;
    overflow-y: auto;
    padding: 14px;
  }
</style>
